package com.acme.ionio;

import com.acme.ionio.impl.FileCopierClientIO;
import com.acme.ionio.impl.FileCopierClientNIO;
import com.acme.ionio.impl.FileCopierServerIO;
import com.acme.ionio.impl.FileCopierServerNIO;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;

/**
 * 1) Command line arguments to run client:
 * {io|nio} client {url} {port} {file to copy}
 * 2) Command line arguments to run server:
 * {io|nio} server {port to bind} {file to write} [loop]
 * if you write loop at the end - server will accept clients in loop
 * @author Gregory Sobko
 */
public class MainNet {

    private static Logger logger = Logger.getLogger(MainNet.class);
    
    public static void main(String... args) throws InterruptedException, IOException {
        if(args.length < 5){
            
            
            logger.error("Not enough arguments: specify " +
                    "'{nio|io} { client {url} {port} {from file} | server {port} {to file} [loop] }");
            return;
        }
        if ("server".equals(args[1])) {
            logger.info("Running server...");
            runServer(args[2], args[3], "nio".equals(args[0]),
                    args.length >= 5 && "loop".equals(args[4]));
        } else if("client".equals(args[1])) {
            runClient(args[2], args[3], args[4], "nio".equals(args[0]));
        } else {
            logger.error("Wrong input given!");
        }
    }

    private static void runServer(String port, String to, boolean nio, boolean loop) throws IOException {

        FileCopierServer fileCopierServer = null;
        if (nio) {
            logger.info("Using NIO server");
            fileCopierServer = new FileCopierServerNIO();
        } else {
            logger.info("Using IO server");
            fileCopierServer = new FileCopierServerIO();
        }
        do{
            fileCopierServer.copy(new File(to), Integer.parseInt(port));
        } while (loop);
    }

    private static void runClient(String url, String port, String from, boolean nio){
        FileCopierClient fileCopierClient = null;
        if (nio) {
            logger.info("Using NIO client");
            fileCopierClient = new FileCopierClientNIO();
        } else {
            logger.info("Using IO client");
            fileCopierClient = new FileCopierClientIO();
        }

        long start = System.currentTimeMillis();
        try {
            fileCopierClient.copy(new File(from), url, Integer.parseInt(port));
        } catch (IOException e) {
            logger.info("Cannot copy file: " + e.getMessage());
        }
        logger.info("Time consumed: " + (System.currentTimeMillis() - start) + " ms");
    }


}


